﻿using CN2P.Recommendations.DomainModel;
using CN2P.Recommendations.Repository.Impl;
using CN2P.Recommendations.Repository.Interfaces;
using CN2P.Recommendations.WebApi.Properties;
using Microsoft.WindowsAzure.ServiceRuntime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace CN2P.Recommendations.WebApi.Controllers
{
    public class RecommendationController : ApiController
    {
        private IProductRecommendationRepository _repository;

        //TODO: Remove when dependency injection is fully implemented
        public RecommendationController() :
            this(new Neo4jRepositoryImplementation(new Uri(
                RoleEnvironment.IsAvailable ?
                    RoleEnvironment.GetConfigurationSettingValue("Neo4JUrl") : 
                    Settings.Default.Neo4JUrl)))
        {
        }

        public RecommendationController(IProductRecommendationRepository repository)
        {
            _repository = repository;
        }

        // GET /api/recommendation/?prodId=1&prodId=2&prodId=999
        public string[] Get([FromUri]string[] prodId)
        {
            var result = new List<string>();

            var recommendations = _repository.GetRecommendations(prodId);

            foreach (var recommendation in recommendations)
            {
                result.Add(recommendation.ProductId);
            }

            return result.ToArray();
        }

        [HttpPost]
        [ActionName("Traversal")]
        public HttpResponseMessage PostTraversal([FromBody]Traversal traversal)
        {
            _repository.AddRecommendationTraversal(traversal.From, traversal.To);
            return new HttpResponseMessage(HttpStatusCode.Created);
        }

        [HttpPost]
        [ActionName("Rating")]
        public HttpResponseMessage PostRating([FromBody]ProductRating rating)
        {
            _repository.SubmitProductRating(rating.ProductId, rating.AverageRating);
            return new HttpResponseMessage(HttpStatusCode.Created);
        }
    }
}
